'''
Created on 2011-7-28

@author: Johnny
'''
import os, copy
from util.util import Util
from util.xmlparse import XmlParser
root = Util.get_root_path()

class Result(object):
    '''
    classdocs
    '''
    
    @staticmethod
    def deal_result(case):
        '''
        Collect test results and write to xml files for each case.
        @params:
        case -- case list with steps' results
        '''
        print 'resultdeal -- deal_result '
        try:
            case_list = copy.deepcopy(case)  
            case_name = case_list.pop(0)
            time_stamp = case_list.pop(0)
            
            # Save screenshots if case failed
            case_result = Result.is_case_failed(case_list)
            print 'resultdeal -- caseresult: ' + str(case_result)
            if case_result:
                Result.save_screenshots(case_name, case_list, time_stamp)
                
            # Write result to xml file
            case_list.insert(0, case_name)
            case_list.insert(1, case_result)
            case_list.insert(2, time_stamp)
            xml_name = root + "/Results/" + case_name + "_results.xml"
            xml_parser = XmlParser(xml_name)
            xml_parser.write_xml_report(case_list)
        except Exception, e:
            print 'resultdeal -- deal_result: Exception = ' + str(e)
        
    @staticmethod
    def is_case_failed(case):
        '''
        Judge whether case is failed or not.
        @params:
        case -- case list with steps' results
        @return:
        True -- if there is at least one failed step
        False -- if no failed step
        '''
        print 'resultdeal -- is_case_failed '
        for step in case:
            print 'Result -- step.result: ' + step.result
            if step.result is "Failed":
                return True
        return False
    
    @staticmethod
    def save_screenshots(case_name, case, time_stamp):
        '''
        Save screenshots to sub folder 'screenshots'.
        @params:
        case -- case list with steps' results
        '''        
        try:
            # Make screenshots folder
            print 'resultdeal -- save_screenshots '
            scrshot_path = root + "/Results/" + case_name + "_screenshots_" + time_stamp + "/"
            if not os.path.exists(scrshot_path):
                os.makedirs(scrshot_path)
                
            # Save screenshots for every step
            for step in case:
                save_name = scrshot_path + step.name + ".png"
                Util.pic_decoder(step.step_pic, save_name)
                step.step_pic = save_name
        except Exception, e:
            print 'resultdeal -- ' + str(e)